﻿using System;
using System.Linq;
using Coolite.Ext.Web;
using Pap.Data;
using Pap.Web.Modules.Loan.ViewModel;
using Pap.Web.Utils;
using Utils.UIPermission;

namespace Pap.Web.Modules.Loan.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FeasibilityStudy : BaseUserControl<FeasibilityStudyViewModel>, IPermittedPage
    {
        #region QueryString Variables
        /// <summary>
        /// Gets the current loan ID.
        /// </summary>
        public string CurrentLoanID
        {
            get
            {
                return Request.QueryString["LoanID"];
            }
        }
        #endregion

        #region Event Handlers
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!Ext.IsAjaxRequest)
                {
                    storePaymentMethods.DataSource = this.ViewModel.GetAllPaymentMethods();
                    storePaymentMethods.DataBind();

                    txtTaxes.Value = this.ViewModel.GetTaxValue();
                    IProjectStage stage = this.ViewModel.GetLoanProject(CurrentLoanID);

                    txtProjectProfit.Text = stage.ProjectObj.ProfitPercent.ToString();
                    txtProposedAmount.MinValue = stage.From;
                    txtProposedAmount.MaxValue = stage.To;

                    FillCustomerInfo();
                    FillFeasibilityStudyInfo();
                }
            }
        }

        /// <summary>
        /// Handles the Clicked event of the btnAccept control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnAccept_Clicked(object sender, AjaxEventArgs args)
        {
            if (rdoAcceptStudy.Checked)
                SaveFeasibilityStudy();
            else if (rdoRefuseStudy.Checked)
                RefuseFeasibilityStudy();
            else if (rdoFreezeStudy.Checked)
                FreezeFeasibilityStudy();

        }


        /// <summary>
        /// Handles the Clicked event of the btnBack control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnBack_Clicked(object sender, AjaxEventArgs args)
        {
            this.RedirectToPreviousPage();
        }
        #endregion

        #region Private Functions

        /// <summary>
        /// Fills the feasibility study info.
        /// </summary>
        private void FillFeasibilityStudyInfo()
        {
            this.dateFreezeStudy.Hidden = true;
            this.rdoAcceptStudy.Checked = true;
            //-------------------------------------------------------------------------------------------------------
            ILoanFeasibilityStudy currentFeasibilityStudy = this.ViewModel.GetFeasibilityStudyForLoan(CurrentLoanID);
            if (currentFeasibilityStudy != null)
            {
                txtProposedAmount.Text = currentFeasibilityStudy.LoanAmount.ToString();
                txtProposedPaymentPeriod.Text = currentFeasibilityStudy.LoanPaymentPeriod.ToString();
                txtTotalIncome.Text = currentFeasibilityStudy.RevenueAmount.ToString();
                txtTotalExpenses.Text = currentFeasibilityStudy.CostAmount.ToString();
                txtROI.Text = currentFeasibilityStudy.ReturnOnInvestmentPercent.ToString();
                txtNetProfit.Text = currentFeasibilityStudy.ProfitAmount.ToString();
                txtInstallmentAmount.Text = Math.Round(currentFeasibilityStudy.LoanAmount / (double)currentFeasibilityStudy.LoanPaymentPeriod, 2).ToString("F");
                txtNotesFeasbility.Text = currentFeasibilityStudy.Notes;
                cmbPaymentMethods.SelectedItem.Value = currentFeasibilityStudy.LoanPaymentMethodID.ToString();

                insertAttachmentsFeasability.SetImages(currentFeasibilityStudy.Attachements.Select(att => att.AttachmentImage));
            }
        }

        /// <summary>
        /// Fills the customer info.
        /// </summary>
        private void FillCustomerInfo()
        {
            var currentLoan = this.ViewModel.GetLoan(CurrentLoanID);
            this.txtName.Text = currentLoan.CustomerObj.CustomerName;
            this.txtNationalID.Text = currentLoan.CustomerObj.SSN;
            this.txtProposedAmount.Text = currentLoan.LoanAmount.ToString();
            this.txtProposedPaymentPeriod.Text = currentLoan.LoanPaymentPeriod.ToString();
            this.cmbPaymentMethods.SelectedItem.Value = currentLoan.LoanPaymentMethodID.ToString();
            txtInstallmentAmount.Text = ((currentLoan.LoanAmount + (currentLoan.LoanAmount * (double)currentLoan.ProjectStage.ProjectObj.ProfitPercent / 100)) / currentLoan.LoanPaymentPeriod).ToString("F");
            insertAttachmentsFeasability.ExtraLabel = string.Format("{0}, {1}, ", currentLoan.CustomerObj.CustomerName, currentLoan.LoanNumber);
        }

        /// <summary>
        /// Saves the feasibility study.
        /// </summary>
        private void SaveFeasibilityStudy()
        {
            try
            {
                var insertedAttachmentIds = insertAttachmentsFeasability.GetInsertedIDs();
                var deletedAttachemnetsIds = insertAttachmentsFeasability.GetDeletedIDs();
                insertAttachmentsFeasability.Save();
                this.ViewModel.SaveFeasibilityStudy(CurrentLoanID, insertedAttachmentIds, deletedAttachemnetsIds, txtProposedAmount.Text, txtProposedPaymentPeriod.Text,
                    txtTotalIncome.Text, txtTotalExpenses.Text, txtROI.Text,
                    txtInstallmentAmount.Text, txtNotesFeasbility.Text, cmbPaymentMethods.SelectedItem.Value,
                    Pap.Services.WorkflowEngine.ActionTypes.Submit, null);
                lblState.Visible = true;

                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.INFO,
                    Title = GetLocalResourceObject("MBSave").ToString(),
                    Message = GetLocalResourceObject("MSGSave").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
                this.RedirectToPreviousPage();
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("MBError").ToString(),
                    Message = GetLocalResourceObject("MSGError").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
        }
        /// <summary>
        /// Freezes the feasibility study.
        /// </summary>
        private void FreezeFeasibilityStudy()
        {
            try
            {
                var insertedAttachmentIds = insertAttachmentsFeasability.GetInsertedIDs();
                var deletedAttachemnetsIds = insertAttachmentsFeasability.GetDeletedIDs();
                insertAttachmentsFeasability.Save();

                DateTime? CompletionDate = Convert.ToDateTime(dateFreezeStudy.Value);

                this.ViewModel.SaveFeasibilityStudy(CurrentLoanID, insertedAttachmentIds, deletedAttachemnetsIds, txtProposedAmount.Text, txtProposedPaymentPeriod.Text,
                    txtTotalIncome.Text, txtTotalExpenses.Text, txtROI.Text,
                    txtInstallmentAmount.Text, txtNotesFeasbility.Text, cmbPaymentMethods.SelectedItem.Value,
                    Pap.Services.WorkflowEngine.ActionTypes.Freeze, CompletionDate);
                lblState.Visible = true;

                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.INFO,
                    Title = GetLocalResourceObject("MBFreeze").ToString(),
                    Message = GetLocalResourceObject("MSGFreeze").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
                this.RedirectToPreviousPage();
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("MBError").ToString(),
                    Message = GetLocalResourceObject("MSGError").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
        }
        /// <summary>
        /// Refuses the feasibility study.
        /// </summary>
        private void RefuseFeasibilityStudy()
        {
            try
            {
                var insertedAttachmentIds = insertAttachmentsFeasability.GetInsertedIDs();
                var deletedAttachemnetsIds = insertAttachmentsFeasability.GetDeletedIDs();
                insertAttachmentsFeasability.Save();


                this.ViewModel.SaveFeasibilityStudy(CurrentLoanID, insertedAttachmentIds, deletedAttachemnetsIds, txtProposedAmount.Text, txtProposedPaymentPeriod.Text,
                    txtTotalIncome.Text, txtTotalExpenses.Text, txtROI.Text,
                    txtInstallmentAmount.Text, txtNotesFeasbility.Text, cmbPaymentMethods.SelectedItem.Value,
                    Pap.Services.WorkflowEngine.ActionTypes.Refuse, null);
                lblState.Visible = true;

                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.INFO,
                    Title = GetLocalResourceObject("MBRefuse").ToString(),
                    Message = GetLocalResourceObject("MSGRefuse").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
                this.RedirectToPreviousPage();
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("MBError").ToString(),
                    Message = GetLocalResourceObject("MSGError").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
        }

        #endregion

        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "FeasibilityStudy"; }
        }

        #endregion

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="FeasibilityStudy"/> is hidden.
        /// </summary>
        /// <value>
        ///   <c>true</c> if hidden; otherwise, <c>false</c>.
        /// </value>
        public bool Hidden
        {
            set
            {
                this.pnlStudy.Hidden = value;
            }
            get
            {
                return this.pnlStudy.Hidden;
            }
        }

    }
}
